<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 顶部组件 -->
      <PageTool
        ref="PageTool"
        btn-name="分类"
        :show-search="true"
        @searchEvent="searchFn"
        @addEvent="addFn"
      />
      <!-- 主体内容 -->
      <el-card>
        <el-table :data="formData" border>
          <el-table-column label="图片" prop="image">
            <template v-slot="{ row }">
              <img :src="row.image" alt="" width="200px" height="200px">
            </template>
          </el-table-column>
          <el-table-column label="标题" prop="title" />
          <el-table-column label="介绍" prop="desc" />
          <el-table-column label="操作" width="200px">
            <template v-slot="{ row }">
              <el-col>
                <el-button
                  size="small"
                  type="primary"
                  @click="editFn(row.id)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="delFn(row.id)"
                >删除</el-button>
              </el-col>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-row type="flex" justify="center">
          <el-pagination
            v-if="showPagin"
            layout="prev, pager, next,total"
            :total="total"
            :page-size="pageData._limit"
            @current-change="currentChangeFn"
          />
        </el-row>
      </el-card>
      <!-- 弹窗组件 -->
      <el-dialog
        :title="form.id ? '编辑分类' : '新增分类'"
        :visible="showDialog"
        @close="closeFn"
      >
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="标题" label-width="50px" prop="title">
            <el-input v-model.trim="form.title" />
          </el-form-item>
          <el-form-item label="描述" label-width="50px" prop="desc">
            <el-input v-model.trim="form.desc" />
          </el-form-item>
          <el-form-item label="封面" label-width="50px">
            <!-- 图片上传组件 -->
            <ImageUpload ref="imageUpload" img-type="image" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button
            size="small"
            type="primary"
            @click="confirmFn"
          >确定</el-button>
          <el-button size="small" @click="closeFn">取消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getCategories,
  assignCate,
  categoriesCount,
  editCategories,
  addCategories,
  delCategories
} from '@/api/categories'
import ImageUpload from '@/components/imageUpload'
import PageTool from '@/components/PageTool'
// 腾讯云图像上传
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDUmpfFXZKo0zi9JCo9CyUkiPpyqRknY2E',
  SecretKey: 'xd18zZsuCH5dttc3D6j5AxUlmX3JJ3bu'
})
export default {
  components: {
    ImageUpload,
    PageTool
  },
  data() {
    return {
      formData: [
        // 请求回来的数据保存
        {
          image: '',
          title: '',
          desc: ''
        }
      ],
      showDialog: false, // 弹窗显示
      form: {
        // //弹窗表单内容
        title: '',
        desc: ''
      },
      pageData: {
        _limit: 2, // 每页至少limit条数据
        _start: 0 // 每页数据的开始下标值
      },
      total: 0, // 数据总量
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '标题只能是1-10个字符',
            trigger: 'blur'
          }
        ],
        desc: [
          { required: true, message: '介绍不能为空', trigger: 'blur' },
          {
            min: 5,
            max: 300,
            message: '介绍只能是5-300个字符',
            trigger: 'blur'
          }
        ]
      },
      // fileList: [], //文件上传
      search: '',
      showPagin: false // 分页器的显示控制
    }
  },
  async created() {
    await this.getCateList()
    // 数据总条数
    // await this.getcateCount();
  },
  methods: {
    // 分类列表的封装
    async getCateList() {
      const { data } = await getCategories({
        _limit: this.pageData._limit,
        _start: this.pageData._start
      })
      this.formData = data
      this.showPagin = true
      await this.getcateCount()
    },
    // 获取分类列表总数量
    async getcateCount() {
      const { data } = await categoriesCount()
      this.total = data
    },
    // 搜素功能
    async searchFn() {
      const res = await getCategories({
        title_contains: this.$refs.PageTool.searchKey
      })
      this.formData = res.data
    },
    // 新增分类
    addFn() {
      this.showDialog = true
    },
    // 编辑数据
    async editFn(id) {
      // 请求获取指定分类接口,回显数据
      const { data } = await assignCate(id)
      this.form = data
      console.log(198, this.form)
      // 图片的回显--将filelist的url
      this.$nextTick(() => {
        this.$refs.imageUpload.fileList.push({ url: data.image })
      })
      // 弹窗显示
      this.showDialog = true
    },
    // 弹窗中确定按钮事件
    async confirmFn() {
      //   编辑后，再次进入表单验证
      await this.$refs.form.validate()
      const file = this.$refs.imageUpload.fileList[0].url
      console.log(215, file)
      if (this.form.id) {
        // 编辑不成立
        await editCategories({
          ...this.form,
          image: file,
          id: this.form.id
        })
        this.$message.success('编辑成功')
      } else {
        // 新增分类
        await addCategories({
          ...this.form,
          image: file
        });
        (this.pageData = {
          _limit: 2, // 每页至少limit条数据
          _start: 0 // 每页数据的开始下标值
        }),
        await this.getCateList()
        this.$message.success('新增成功')
      }
      // 关闭弹窗
      this.closeFn()
      // 重新请求分类列表，刷新页面
      this.getCateList()
    },
    // 删除数据
    delFn(id) {
      // 二次确定
      this.$confirm('确定删除吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 确定删除--删除分类接口
          await delCategories(id);
          (this.pageData = {
            _limit: 2, // 每页至少limit条数据
            _start: 0 // 每页数据的开始下标值
          }),
          // 刷新页面
          this.getCateList()
          // 重新获取数据总数
          await categoriesCount()
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message.warning('取消删除')
        })
    },
    // 弹窗的关闭按钮
    closeFn() {
      // 弹窗关闭后，清除校验规则和清空数据
      this.$refs.form.resetFields()
      this.showDialog = false
      this.form = { title: '', desc: '' }
      this.$refs.imageUpload.fileList = []
    },
    // 页码改变触发的函数
    currentChangeFn(val) {
      this.pageData._start = (val - 1) * this.pageData._limit
      // 修改数据之后，再次发请求数据渲染
      this.getCateList()
    },
    // 上传图片在页面中显示
    onChange(file) {
      // console.log(207, file);
      this.fileList.push({
        url: file.url
      })
    },
    // 真正实现上传的函数---自定义上传的
    uploadFn(file) {
      this.$refs.imageUpload.uploadFn()
    },
    // 照片移除--清空fileList数据
    handleRemove() {
      this.$refs.imageUpload.removeFn()
    }
  }
}
</script>

<style lang="scss" >
.disable {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
